using BXS.API.Models;
using BXS.API.Services;
using Microsoft.AspNetCore.Mvc;

namespace BXS.API.Controllers
{
    /// <summary>
    /// 订单管理控制器
    /// </summary>
    public class OrdersController : BaseController
    {
        private readonly WeChatPayService _wechatPayService;

        public OrdersController(WeChatPayService wechatPayService)
        {
            _wechatPayService = wechatPayService;
        }
        // 模拟数据
        private static List<Order> _orders = new List<Order>
        {
            new Order 
            { 
                Id = 1, 
                OrderNo = "ORD20250101001", 
                CustomerName = "张三", 
                CustomerPhone = "13800138001", 
                TotalAmount = 1680, 
                Status = "pending", 
                PaymentMethod = "微信支付", 
                CreateTime = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd HH:mm:ss"),
                Products = new List<OrderProduct>
                {
                    new OrderProduct { Name = "寿衣", Quantity = 1, Price = 1680 }
                }
            },
            new Order 
            { 
                Id = 2, 
                OrderNo = "ORD20250102001", 
                CustomerName = "李四", 
                CustomerPhone = "13800138002", 
                TotalAmount = 2999, 
                Status = "paid", 
                PaymentMethod = "微信支付", 
                CreateTime = DateTime.Now.AddDays(-6).ToString("yyyy-MM-dd HH:mm:ss"),
                Products = new List<OrderProduct>
                {
                    new OrderProduct { Name = "玉石骨灰盒", Quantity = 1, Price = 2999 }
                }
            },
            new Order 
            { 
                Id = 3, 
                OrderNo = "ORD20250103001", 
                CustomerName = "王五", 
                CustomerPhone = "13800138003", 
                TotalAmount = 299, 
                Status = "processing", 
                PaymentMethod = "微信支付", 
                CreateTime = DateTime.Now.AddDays(-5).ToString("yyyy-MM-dd HH:mm:ss"),
                Products = new List<OrderProduct>
                {
                    new OrderProduct { Name = "白菊花束", Quantity = 1, Price = 299 }
                }
            },
            new Order 
            { 
                Id = 4, 
                OrderNo = "ORD20250104001", 
                CustomerName = "赵六", 
                CustomerPhone = "13800138004", 
                TotalAmount = 899, 
                Status = "completed", 
                PaymentMethod = "微信支付", 
                CreateTime = DateTime.Now.AddDays(-4).ToString("yyyy-MM-dd HH:mm:ss"),
                Products = new List<OrderProduct>
                {
                    new OrderProduct { Name = "纸扎祭品", Quantity = 1, Price = 899 }
                }
            },
            new Order 
            { 
                Id = 5, 
                OrderNo = "ORD20250105001", 
                CustomerName = "孙七", 
                CustomerPhone = "13800138005", 
                TotalAmount = 1299, 
                Status = "cancelled", 
                PaymentMethod = "微信支付", 
                CreateTime = DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd HH:mm:ss"),
                Products = new List<OrderProduct>
                {
                    new OrderProduct { Name = "悼念花圈", Quantity = 1, Price = 1299 }
                }
            },
            new Order 
            { 
                Id = 6, 
                OrderNo = "ORD20250106001", 
                CustomerName = "周八", 
                CustomerPhone = "13800138006", 
                TotalAmount = 1680, 
                Status = "paid", 
                PaymentMethod = "微信支付", 
                CreateTime = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd HH:mm:ss"),
                Products = new List<OrderProduct>
                {
                    new OrderProduct { Name = "寿衣", Quantity = 1, Price = 1680 }
                }
            },
            new Order 
            { 
                Id = 7, 
                OrderNo = "ORD20250107001", 
                CustomerName = "吴九", 
                CustomerPhone = "13800138007", 
                TotalAmount = 2999, 
                Status = "processing", 
                PaymentMethod = "微信支付", 
                CreateTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss"),
                Products = new List<OrderProduct>
                {
                    new OrderProduct { Name = "玉石骨灰盒", Quantity = 1, Price = 2999 }
                }
            },
            new Order 
            { 
                Id = 8, 
                OrderNo = "ORD20250108001", 
                CustomerName = "郑十", 
                CustomerPhone = "13800138008", 
                TotalAmount = 598, 
                Status = "completed", 
                PaymentMethod = "微信支付", 
                CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                Products = new List<OrderProduct>
                {
                    new OrderProduct { Name = "白菊花束", Quantity = 2, Price = 299 }
                }
            }
        };

        /// <summary>
        /// 获取订单列表
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="pageSize">每页大小</param>
        /// <param name="status">状态筛选</param>
        /// <returns>订单列表</returns>
        [HttpGet]
        public ActionResult<PagedApiResponse<Order>> GetOrders([FromQuery] int page = 1, [FromQuery] int pageSize = 10, [FromQuery] string? status = null)
        {
            var query = _orders.AsQueryable();
            
            if (!string.IsNullOrEmpty(status) && status != "all")
            {
                query = query.Where(o => o.Status == status);
            }

            var total = query.Count();
            var skip = (page - 1) * pageSize;
            var orders = query.OrderByDescending(o => o.CreateTime).Skip(skip).Take(pageSize).ToList();
            
            return PagedSuccess(orders, total, page, pageSize);
        }

        /// <summary>
        /// 根据ID获取订单
        /// </summary>
        /// <param name="id">订单ID</param>
        /// <returns>订单信息</returns>
        [HttpGet("{id}")]
        public ActionResult<ApiResponse<Order>> GetOrder(int id)
        {
            var order = _orders.FirstOrDefault(o => o.Id == id);
            if (order == null)
            {
                return Error<Order>("订单不存在", 404);
            }
            return Success(order);
        }

        /// <summary>
        /// 创建订单并支付
        /// </summary>
        /// <param name="request">创建订单请求</param>
        /// <returns>创建结果</returns>
        [HttpPost]
        public async Task<ActionResult<ApiResponse<Order>>> CreateOrder([FromBody] CreateOrderRequest request)
        {
            if (string.IsNullOrEmpty(request.CustomerName) || string.IsNullOrEmpty(request.CustomerPhone) || !request.Products.Any())
            {
                return Error<Order>("请填写完整信息");
            }

            var totalAmount = request.Products.Sum(p => p.Price * p.Quantity);
            var orderNo = $"ORD{DateTime.Now:yyyyMMdd}{_orders.Count + 1:D3}";

            var newOrder = new Order
            {
                Id = _orders.Count > 0 ? _orders.Max(o => o.Id) + 1 : 1,
                OrderNo = orderNo,
                CustomerName = request.CustomerName,
                CustomerPhone = request.CustomerPhone,
                TotalAmount = totalAmount,
                Status = "pending",
                PaymentMethod = request.PaymentMethod,
                CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                Products = request.Products
            };

            _orders.Add(newOrder);

            // 调用微信支付API
            var paymentResult = await _wechatPayService.UnifiedOrderAsync(newOrder);
            if (paymentResult.Success)
            {
                // 支付成功，更新订单状态
                newOrder.Status = "paid";
                return Success(newOrder, "订单创建并支付成功");
            }
            else
            {
                // 支付失败，删除订单
                _orders.Remove(newOrder);
                return Error<Order>(paymentResult.Message);
            }
        }

        /// <summary>
        /// 更新订单状态
        /// </summary>
        /// <param name="id">订单ID</param>
        /// <param name="request">状态更新请求</param>
        /// <returns>更新结果</returns>
        [HttpPut("{id}/status")]
        public ActionResult<ApiResponse<Order>> UpdateOrderStatus(int id, [FromBody] UpdateOrderStatusRequest request)
        {
            var order = _orders.FirstOrDefault(o => o.Id == id);
            if (order == null)
            {
                return Error<Order>("订单不存在", 404);
            }

            if (string.IsNullOrEmpty(request.Status))
            {
                return Error<Order>("状态不能为空");
            }

            order.Status = request.Status;
            return Success(order, "订单状态更新成功");
        }

        /// <summary>
        /// 删除订单
        /// </summary>
        /// <param name="id">订单ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public ActionResult<ApiResponse<bool>> DeleteOrder(int id)
        {
            var order = _orders.FirstOrDefault(o => o.Id == id);
            if (order == null)
            {
                return Error<bool>("订单不存在", 404);
            }

            _orders.Remove(order);
            return Success(true, "订单删除成功");
        }

        /// <summary>
        /// 获取订单状态列表
        /// </summary>
        /// <returns>状态列表</returns>
        [HttpGet("statuses")]
        public ActionResult<ApiResponse<List<string>>> GetStatuses()
        {
            var statuses = _orders.Select(o => o.Status).Distinct().ToList();
            return Success(statuses);
        }
    }
} 